#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
示例运行脚本
用于运行和测试所有示例
"""

import argparse
import sys
from pathlib import Path

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from generate_video.core.config import Config
from generate_video.core.pipeline import VideoPipeline
from generate_video.parsers.markdown_parser import MarkdownParser


def run_single_example(markdown_file, output_dir=None, quality="standard", theme="dark"):
    """
    运行单个示例

    Args:
        markdown_file: Markdown文件路径
        output_dir: 输出目录
        quality: 质量级别
        theme: 主题

    Returns:
        bool: 是否成功
    """
    try:
        # 读取Markdown文件
        with open(markdown_file, "r", encoding="utf-8") as f:
            markdown_content = f.read()

        # 解析Markdown
        parser = MarkdownParser()
        metadata, scenes = parser.parse(markdown_content)

        # 创建配置
        config = Config({
            "outdir": output_dir or f"outputs/{markdown_file.stem}",
            "quality": quality,
            "theme": theme,
            "fps": 30,
            "resolution": "1920x1080"
        })

        # 创建输出目录
        output_path = Path(config.outdir)
        output_path.mkdir(parents=True, exist_ok=True)

        # 简单验证：检查解析结果
        assert isinstance(metadata, dict), "元数据解析失败"
        assert isinstance(scenes, list), "场景解析失败"
        assert len(scenes) > 0, "没有找到场景"

        # 记录示例信息
        print(f"\n✅ 示例验证成功: {markdown_file.name}")
        print(f"   场景数量: {len(scenes)}")
        print(f"   输出目录: {output_path}")
        print(f"   质量设置: {quality}")
        print(f"   主题: {theme}")

        # 保存解析结果用于验证
        import json
        result_file = output_path / "parsed_result.json"
        with open(result_file, "w", encoding="utf-8") as f:
            json.dump({
                "metadata": metadata,
                "scenes": scenes,
                "scene_count": len(scenes)
            }, f, ensure_ascii=False, indent=2)

        return True

    except Exception as e:
        print(f"\n❌ 示例验证失败: {markdown_file.name}")
        print(f"   错误: {str(e)}")
        return False


def run_all_examples(level=None, output_base="outputs"):
    """
    运行所有示例

    Args:
        level: 难度级别 (basic/intermediate/advanced)
        output_base: 输出基础目录

    Returns:
        dict: 运行结果统计
    """
    examples_dir = Path(__file__).parent

    # 收集所有示例文件
    example_files = []

    if level == "basic":
        example_files = list((examples_dir / "basic").glob("*.md"))
    elif level == "intermediate":
        example_files = list((examples_dir / "intermediate").glob("*.md"))
    elif level == "advanced":
        example_files = list((examples_dir / "advanced").glob("*.md"))
    else:
        # 所有示例
        example_files = list(examples_dir.glob("*.md"))
        example_files.extend(list((examples_dir / "basic").glob("*.md")))
        example_files.extend(list((examples_dir / "intermediate").glob("*.md")))
        example_files.extend(list((examples_dir / "advanced").glob("*.md")))

    # 去重并排序
    example_files = sorted(list(set(example_files)))

    # 统计信息
    stats = {
        "total": len(example_files),
        "success": 0,
        "failed": 0,
        "results": []
    }

    print("=" * 80)
    print("开始运行示例验证")
    print("=" * 80)

    for example_file in example_files:
        print(f"\n📄 处理示例: {example_file.name}")
        success = run_single_example(example_file, output_base)

        stats["results"].append({
            "file": example_file.name,
            "success": success
        })

        if success:
            stats["success"] += 1
        else:
            stats["failed"] += 1

    # 打印统计信息
    print("\n" + "=" * 80)
    print("运行完成！")
    print("=" * 80)
    print(f"总示例数: {stats['total']}")
    print(f"成功: {stats['success']}")
    print(f"失败: {stats['failed']}")
    print(f"成功率: {stats['success'] / max(stats['total'], 1) * 100:.1f}%")
    print("=" * 80)

    return stats


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="运行示例验证")
    parser.add_argument(
        "--file",
        type=Path,
        help="运行指定的示例文件"
    )
    parser.add_argument(
        "--output",
        type=Path,
        help="输出目录"
    )
    parser.add_argument(
        "--level",
        type=str,
        choices=["basic", "intermediate", "advanced"],
        help="按难度级别运行"
    )
    parser.add_argument(
        "--quality",
        type=str,
        default="standard",
        choices=["preview", "standard", "high", "ultra"],
        help="质量设置"
    )
    parser.add_argument(
        "--theme",
        type=str,
        default="dark",
        choices=["dark", "light", "academic", "presentation"],
        help="主题设置"
    )

    args = parser.parse_args()

    # 运行单个示例
    if args.file:
        if not args.file.exists():
            print(f"错误: 文件不存在 {args.file}")
            sys.exit(1)

        success = run_single_example(
            args.file,
            args.output,
            args.quality,
            args.theme
        )
        sys.exit(0 if success else 1)

    # 运行所有示例
    else:
        stats = run_all_examples(args.level)
        sys.exit(0 if stats["failed"] == 0 else 1)


if __name__ == "__main__":
    main()
